package org.skydiveapp2;

import java.util.ArrayList;
import java.util.List;

import org.skydiveapp2.ui.InterfaceManager;
import org.skydiveapplibrary.data.Aircraft;
import org.skydiveapplibrary.data.Database;
import org.skydiveapplibrary.data.JumpYear;
import org.skydiveapplibrary.data.Location;
import org.skydiveapplibrary.data.Rig;
import org.skydiveapplibrary.data.SkydiveType;
import org.skydiveapplibrary.repository.AircraftRepository;
import org.skydiveapplibrary.repository.LocationRepository;
import org.skydiveapplibrary.repository.RigRepository;
import org.skydiveapplibrary.repository.SkydiveTypeRepository;
import org.skydiveapplibrary.ui.FormatUtility;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class SummaryExtendedActivity extends Activity {

	private boolean showAllRigs = false;
	
	private enum TableRowLocation
	{
		First,
		Middle,
		Last,
		Solo
	};
	
	// repositories
	private RigRepository rigRepository = new RigRepository(this);
	private AircraftRepository aircraftRepository = new AircraftRepository(this);
	private LocationRepository locationRepository = new LocationRepository(this);
	private SkydiveTypeRepository skydiveTypeRepository = new SkydiveTypeRepository(this);
	
	// jumps by year count query
	private static final String JUMPS_BY_YEAR_QUERY =
		"select count(*) as Jumps, strftime('%Y', Date) as Year " +
		"from log_entry " +
		"group by Year " +
		"order by Year desc";
		
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(initializeUI());
		
		overridePendingTransition(R.anim.fadein,
				R.anim.hold);
	}
    
	private View initializeUI()
	{
		//Main LinearLayout
		LinearLayout mainLL = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.summary_extended_view, null);
		
		//set header text	
		if (this.findViewById(R.id.tabletLayout) != null)
		{
			InterfaceManager.getInstance().configureTabletUI(this, 
					R.string.summary_total_jumps_label);
		}
		else
		{
			InterfaceManager.getInstance().configurePhoneUI(this, 
					R.string.summary_total_jumps_label);
		}
		
		//Table Layout
		TableLayout tableL = (TableLayout) mainLL.findViewById(R.id.summaryExtendedTable);

		//Dropzone
		List<Location> locations = locationRepository.getAllLocations();
		
		// Remove unused locations
		for (int i = 0; i < locations.size(); i++)
		{
			if (locations.get(i).getJumpCount() == 0)
			{
				locations.remove(i);
				i--;
			}
		}

		for (int i = 0; i < locations.size(); i++)
		{
			Location location = locations.get(i);
		
			TableRowLocation style = TableRowLocation.First;
		
			if (i == 0)
			{
				tableL.addView(newFormGroupHeader("Per Dropzone", true, null));
			}
			
			if (locations.size() == 1)
			{
				style = TableRowLocation.Solo;
			}
			else if (i == locations.size()-1)
			{
				style = TableRowLocation.Last;
			}
			else if (i > 0)
			{
				style = TableRowLocation.Middle;
			}
			
			tableL.addView(addTableRow(location.getName(), 
							location.getJumpCount() == 0 ? "0" : FormatUtility.toNumericString(location.getJumpCount()),
							style));
		}
		
		
		//Aircraft
		List<Aircraft> aircrafts = aircraftRepository.getAllAircrafts(); 
		
		// Remove unused aircraft
		for (int i = 0; i < aircrafts.size(); i++)
		{
			if (aircrafts.get(i).getJumpCount() == 0)
			{
				aircrafts.remove(i);
				i--;
			}
		}
		
		for (int i = 0; i < aircrafts.size(); i++)
		{
			Aircraft aircraft = aircrafts.get(i);
		
			TableRowLocation style = TableRowLocation.First;
			
			if (i == 0)
			{
				tableL.addView(newFormGroupHeader("Per Aircraft", true, null));
			}
			
			if (aircrafts.size() == 1)
			{
				style = TableRowLocation.Solo;
			}
			else if (i == aircrafts.size()-1)
			{
				style = TableRowLocation.Last;
			}
			else if (i > 0)
			{
				style = TableRowLocation.Middle;
			}
		
			tableL.addView(addTableRow(aircraft.getName(), 
							aircraft.getJumpCount() == 0 ? "0" : FormatUtility.toNumericString(aircraft.getJumpCount()),
							style));

		}
		
		//Rigs
		List<Rig> rigs;
		
		if (showAllRigs == true)
		{
			rigs = rigRepository.getArchivedRigs();
			rigs.addAll(rigRepository.getRigs());
		}
		else
		{
			rigs = rigRepository.getRigs();
		}
		
		for (int i = 0; i < rigs.size(); i++)
		{
			Rig rig = rigs.get(i);
		
			TableRowLocation style = TableRowLocation.First;
		
			if (i == 0)
			{
				tableL.addView(newFormGroupHeader("Per Rig", true, null));
			}
			
			if (rigs.size() == 1)
			{
				style = TableRowLocation.Solo;
			}
			else if (i == rigs.size()-1)
			{
				style = TableRowLocation.Last;
			}
			else if (i > 0)
			{
				style = TableRowLocation.Middle;
			}
		
			tableL.addView(addTableRow(rig.getName(), 
							rig.getJumpCount() == 0 ? "0" : FormatUtility.toNumericString(rig.getJumpCount()),
							style));
		}
		
		
		//Skydive Type
		List<SkydiveType> skydivetypes;
		
		skydivetypes = this.skydiveTypeRepository.getAllSkydiveTypes();
		
		// Remove unused skydive types
		for (int i = 0; i < skydivetypes.size(); i++)
		{
			if (skydivetypes.get(i).getJumpCount() == 0)
			{
				skydivetypes.remove(i);
				i--;
			}
		}
		
		for (int i = 0; i < skydivetypes.size(); i++)
		{
			SkydiveType skydivetype = skydivetypes.get(i);
		
			TableRowLocation style = TableRowLocation.First;
		
			if (i == 0)
			{
				tableL.addView(newFormGroupHeader("Per Skydive Type", true, null));
			}
			
			if (skydivetypes.size() == 1)
			{
				style = TableRowLocation.Solo;
			}
			else if (i == skydivetypes.size()-1)
			{
				style = TableRowLocation.Last;
			}
			else if (i > 0)
			{
				style = TableRowLocation.Middle;
			}

			tableL.addView(addTableRow(skydivetype.getName(), 
							skydivetype.getJumpCount() == 0 ? "0" : FormatUtility.toNumericString(skydivetype.getJumpCount()),
							style));
		}

		
		//Year
		List<JumpYear> jumpyears = GetJumpsByYear();
		
		for (int i = 0; i < jumpyears.size(); i++)
		{
			JumpYear jumpyear = jumpyears.get(i);
		
			TableRowLocation style = TableRowLocation.First;
		
			if (i == 0)
			{
				tableL.addView(newFormGroupHeader("Per Year", true, null));
			}
			
			if (jumpyears.size() == 1)
			{
				style = TableRowLocation.Solo;
			}
			else if (i == jumpyears.size()-1)
			{
				style = TableRowLocation.Last;
			}
			else if (i > 0)
			{
				style = TableRowLocation.Middle;
			}
			
			tableL.addView(addTableRow(jumpyear.getYear(), 
					FormatUtility.toNumericString(jumpyear.getJumps()),
							style));
		}
		
		return mainLL;
	}
	
	public int dp2px(float dp)
	{
		final float scale = getResources().getDisplayMetrics().density;
		return (int) (dp * scale + 0.5f);
	}
	
	private TextView newFormGroupHeader(String strLabel, Boolean blnFirst, OnClickListener listener)
	{
		TextView tv = new TextView(this);
		tv.setText(strLabel);		
		tv.setTextAppearance(this, R.style.FormGroupHeaderStyle);
		
		if (listener != null)
		{
			tv.setOnClickListener(listener);
			tv.setHapticFeedbackEnabled(true);
		}
	
		return tv;
	}
	
	private TableRow addTableRow(String strLabel, String strData, TableRowLocation location)
	{
		//Table Row
		TableRow tr = new TableRow(this);
		TableLayout.LayoutParams tblLayout = new TableLayout.LayoutParams();
		tr.setLayoutParams(tblLayout);
		

		if (location == TableRowLocation.First)
		{
			tr.setBackgroundResource(R.drawable.form_field_top);
			
		}
		else if (location == TableRowLocation.Middle)
		{
			tr.setBackgroundResource(R.drawable.form_field);
		}
		else if (location == TableRowLocation.Last)
		{
			tr.setBackgroundResource(R.drawable.form_field_bottom);
			tblLayout.bottomMargin = 12;
		}
		else if (location == TableRowLocation.Solo)
		{
			tr.setBackgroundResource(R.drawable.form_field_solo);
			tblLayout.bottomMargin = 6;
		}
		
		tr.setMinimumHeight(dp2px(42));
		tr.setGravity(Gravity.CENTER);
		
		//Label
		TextView tvLabel = new TextView(this);
		tvLabel.setTextAppearance(this, R.style.LabelTextAppearanceStyle);
		tvLabel.setText(strLabel);
		
		tvLabel.setGravity(Gravity.RIGHT);
		TableRow.LayoutParams labelLP = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		labelLP.rightMargin = dp2px(10);
		labelLP.weight = 0.65F;
		
		tvLabel.setLayoutParams(labelLP);
		tr.addView(tvLabel);
		
		//Data
		TextView tvData = new TextView(this);
		tvData.setText(strData);
		
		tvData.setGravity(Gravity.LEFT);
		TableRow.LayoutParams dataLP = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		dataLP.weight = 1F;
		tvData.setLayoutParams(dataLP);
	
		tr.addView(tvData);
		
		return tr;
	}
	
	public List<JumpYear> GetJumpsByYear()
	{
		List<JumpYear> jumpyears = new ArrayList<JumpYear>();
		
		Database database = new Database(this);
		SQLiteDatabase db = database.getReadableDatabase();
		Cursor cursor = null;
		try
		{
			// perform query
			cursor = db.rawQuery(JUMPS_BY_YEAR_QUERY, null);
			
			// iterate over results
			while (cursor.moveToNext())
			{
				// create aircrafts
				JumpYear jumpyear = new JumpYear();
				jumpyear.setYear(cursor.getString(1));
				jumpyear.setJumps(cursor.getInt(0));
				jumpyears.add(jumpyear);
			}
		}
		finally
		{
			// close cursor
			if (cursor != null)
			{
				cursor.close();
			}
			// close database
			db.close();
		}
		
		return jumpyears;
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_back, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId())
        {
        case R.id.menu_back:	
        	close();
        	
            return true;
        
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
	@Override
    public void onBackPressed() {
		close();
    }
	
	private void close()
	{
		finish();
    	overridePendingTransition(R.anim.hold,
                R.anim.fadeout);
	}
}
